package com.chen.corejava;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 *@author：email: <a href="cyb@ewppay.com"> Administrator </a> 
 *@Date 2017-2-14 下午3:08:42 
 */

public class CopyOfTest {

	/**
	 * @Description: 扩展数组
	 * @param @param args   
	 * @return void  
	 * @throws
	 * @author cyb
	 * @date 2017-2-14
	 */
	public static void main(String[] args) {
		int[] a = {1,2,3};
		a = (int[]) goodCopyOf(a,10);
		System.out.println(Arrays.toString(a));
		
		String[] b = {"Tom","Dick","Harry"};
		b = (String[]) goodCopyOf(b, 10);
		System.out.println(Arrays.toString(b));
		
		//[Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
		b = (String[]) badCopyOf(b, 10);//java.lang.ClassCastException
	}
	
	public static Object[] badCopyOf(Object[] a, int newLength){
		Object[] newArray = new Object[newLength];
		System.arraycopy(a, 0, newArray, 0, Math.min(a.length, newLength));
		return newArray;
	}
	
	
	@Override
	public String toString() {
		return "CopyOfTest [toString()=" + super.toString() + "]";
	}

	public static Object goodCopyOf(Object a, int newLength){
		Class cl = a.getClass();
		if(!cl.isArray()) return null;
		Class componentType = cl.getComponentType();
		int length = Array.getLength(a);
		Object newArray = Array.newInstance(componentType, newLength);
		System.arraycopy(a, 0, newArray, 0, Math.min(length, newLength));
		return newArray;
	}

}
